package com.bjtu.douyin.utils.AOP;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Aspect
@Component
public class LoggingAspect {
    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    @Around("execution(* com.bjtu.douyin.controller.*.*(..))")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        String logId = UUID.randomUUID().toString();
        MDC.put("logId", logId);

        try {
            Object result = joinPoint.proceed();
            long executionTime = System.currentTimeMillis() - start;
            logger.info("Method " + joinPoint.getSignature().getName() + " execution time: " + executionTime + "ms");
            return result;
        } finally {
            MDC.remove("logId");
        }
    }

    @Before("execution(* com.bjtu.douyin.controller.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        // 记录请求方法的输入
        logger.info("Entering in Method: " + joinPoint.getSignature().getName());
        logger.info("Class Name: " + joinPoint.getSignature().getDeclaringTypeName());
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            logger.info("Argument: " + arg);
        }
    }

    @AfterReturning(pointcut = "execution(* com.bjtu.douyin.controller.*.*(..))", returning = "result")
    public void logAfter(JoinPoint joinPoint, Object result) {
        // 记录请求方法的输出
        logger.info("Method Return value: " + result);
    }
}
